package com.qingzhuge.manager.security.util;

import com.qingzhuge.exception.LoginException;
import com.qingzhuge.manager.dto.SecurityUser;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author zeroxiao
 * @date 2019/9/11 11:04
 * 获取当前登录的用户
 */
public class SecurityUtils {

    public static SecurityUser getUserDetails() {
        SecurityUser userDetails;
        try {
            userDetails = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new LoginException();
        }
        return userDetails;
    }

    /**
     * 获取系统用户名称
     * @return 系统用户名称
     */
    public static String getUsername(){
        SecurityUser user = getUserDetails();
        return user.getUsername();
    }

    /**
     * 获取系统用户id
     * @return 系统用户id
     */
    public static Long getUserId(){
        SecurityUser user = getUserDetails();
        return user.getId();
    }
}
